Geovisualization
Here, I’ll walk you through the code for a geovisualization.
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.4 ✔ purrr 1.0.2
✔ tibble 3.2.1 ✔ dplyr 1.1.4
✔ tidyr 1.3.0 ✔ stringr 1.5.1
✔ readr 2.1.5 ✔ forcats 0.5.2
Warning: package 'readr' was built under R version 4.2.3
Warning: package 'dplyr' was built under R version 4.2.3
Warning: package 'stringr' was built under R version 4.2.3
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag() masks stats::lag()
library(stringr)
library(leaflet)
Warning: package 'leaflet' was built under R version 4.2.3
library(leaflet.extras)
library(tigris)
To enable caching of data, set `options(tigris_use_cache = TRUE)`
in your R script or .Rprofile.
Warning: package 'sf' was built under R version 4.2.3
Linking to GEOS 3.11.0, GDAL 3.5.3, PROJ 9.1.0; sf_use_s2() is TRUE
options(tigris_use_cache = TRUE)
## clean vote data
vote_returns = read.csv("1976-2020-president.csv")
vote_focus <- vote_returns %>%
filter(year == 2020 &
party_simplified == "REPUBLICAN") %>%
mutate(STATEFP = str_pad(state_fips, width = 2, side = "left", pad = "0"),
vote_share = candidatevotes/totalvotes)
## load state polygons
states <- states(year = 2020)
states_leaflet <- states %>%
st_transform(crs = 4326)
## merge state polygons with vote share
state_w_votefocus <- states_leaflet %>%
inner_join(vote_focus, by = "STATEFP")
## create color palette
bins <- quantile(vote_focus$vote_share, probs = seq(from = 0, to = 1, by = 0.2))
palette <- colorBin("YlOrRd", domain = state_w_votefocus$vote_share, bins = bins)
## create labels for each state
state_labels <- sprintf("<strong>State:</strong> %s<br/><strong>Republican Vote Share:</strong> %.2f",
state_w_votefocus$NAME,
state_w_votefocus$vote_share) %>%
lapply(htmltools::HTML)
## create choropleth map
leaflet(state_w_votefocus) %>%
addProviderTiles("OpenStreetMap",
group = "OpenStreetMap") %>%
setView(-96, 37.8, 4) %>%
addPolygons(fillColor = ~palette(vote_share),
weight = 2,
opacity = 1,
color = "white",
fillOpacity = 0.8,
highlightOptions = highlightOptions(
weight = 5,
color = "black",
fillOpacity = 0.8,
bringToFront = TRUE),
label = state_labels) %>%
addLegend(pal = palette, values = ~vote_share, opacity = 0.8,
title = "Republican vote share",
position = "bottomright")